<template>
  <div class="announcement-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="已撤回" value="withdrawn" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>公告列表</span>
          <el-button type="primary" @click="showCreateDialog" :icon="Plus">新建公告</el-button>
        </div>
      </template>

      <el-table :data="announcementList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isTop" type="warning">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="publishedAt" label="发布时间" width="180" />
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editAnnouncement(row)">编辑</el-button>
            <el-button 
              v-if="row.status === 'draft'" 
              size="small" 
              type="success" 
              @click="publishAnnouncement(row.id)"
            >发布</el-button>
            <el-button 
              v-if="row.status === 'published'" 
              size="small" 
              type="warning" 
              @click="withdrawAnnouncement(row.id)"
            >撤回</el-button>
            <el-button 
              size="small" 
              :type="row.isTop ? 'info' : 'warning'" 
              @click="toggleTop(row)"
            >{{ row.isTop ? '取消置顶' : '置顶' }}</el-button>
            <el-button size="small" type="danger" @click="deleteAnnouncement(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: flex-end; margin-top: 12px;">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑公告对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="notice">通知</el-radio>
            <el-radio label="announcement">公告</el-radio>
            <el-radio label="activity">活动</el-radio>
            <el-radio label="maintenance">维护</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="10" 
            placeholder="请输入公告内容，支持HTML格式"
          />
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-switch v-model="formData.isTop" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="info" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="publishNow">发布</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="公告详情" width="700px">
      <div class="detail-content" v-if="currentAnnouncement">
        <div class="detail-item">
          <span class="label">标题：</span>
          <span class="value">{{ currentAnnouncement.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型：</span>
          <el-tag :type="getTypeColor(currentAnnouncement.type)">
            {{ getTypeName(currentAnnouncement.type) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusColor(currentAnnouncement.status)">
            {{ getStatusName(currentAnnouncement.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span class="value">{{ currentAnnouncement.createdAt }}</span>
        </div>
        <div class="detail-item" v-if="currentAnnouncement.publishedAt">
          <span class="label">发布时间：</span>
          <span class="value">{{ currentAnnouncement.publishedAt }}</span>
        </div>
        <div class="detail-item full">
          <span class="label">内容：</span>
          <div class="content" v-html="currentAnnouncement.content"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const searchForm = reactive({
  title: '',
  status: ''
})

const announcementList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const dialogTitle = ref('新建公告')
const formRef = ref(null)
const formData = reactive({
  id: null,
  title: '',
  type: 'notice',
  content: '',
  isTop: false
})

const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
}

const detailVisible = ref(false)
const currentAnnouncement = ref(null)

// 获取公告列表
const getAnnouncementList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/announcement/list', {
      params: {
        title: searchForm.title,
        status: searchForm.status,
        page: page.value,
        pageSize: pageSize.value
      }
    })
    if (response.code === 0) {
      announcementList.value = response.data.list
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getAnnouncementList()
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  searchForm.status = ''
  page.value = 1
  getAnnouncementList()
}

// 分页
const handleCurrentChange = (val) => {
  page.value = val
  getAnnouncementList()
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogTitle.value = '新建公告'
  formData.id = null
  formData.title = ''
  formData.type = 'notice'
  formData.content = ''
  formData.isTop = false
  dialogVisible.value = true
}

// 编辑公告
const editAnnouncement = (row) => {
  dialogTitle.value = '编辑公告'
  formData.id = row.id
  formData.title = row.title
  formData.type = row.type
  formData.content = row.content
  formData.isTop = row.isTop
  dialogVisible.value = true
}

// 保存草稿
const saveAsDraft = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...formData, status: 'draft' }
        const url = formData.id 
          ? `/admin/announcement/update/${formData.id}`
          : '/admin/announcement/create'
        const method = formData.id ? 'put' : 'post'
        
        const response = await request[method](url, data)
        if (response.code === 0) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          getAnnouncementList()
        }
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 发布
const publishNow = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...formData, status: 'published' }
        const url = formData.id 
          ? `/admin/announcement/update/${formData.id}`
          : '/admin/announcement/create'
        const method = formData.id ? 'put' : 'post'
        
        const response = await request[method](url, data)
        if (response.code === 0) {
          ElMessage.success('发布成功')
          dialogVisible.value = false
          getAnnouncementList()
        }
      } catch (error) {
        ElMessage.error('发布失败')
      }
    }
  })
}

// 发布公告
const publishAnnouncement = async (id) => {
  try {
    await ElMessageBox.confirm('确定要发布此公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.post(`/admin/announcement/publish/${id}`)
    if (response.code === 0) {
      ElMessage.success('发布成功')
      getAnnouncementList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

// 撤回公告
const withdrawAnnouncement = async (id) => {
  try {
    await ElMessageBox.confirm('确定要撤回此公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.post(`/admin/announcement/withdraw/${id}`)
    if (response.code === 0) {
      ElMessage.success('撤回成功')
      getAnnouncementList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('撤回失败')
    }
  }
}

// 切换置顶
const toggleTop = async (row) => {
  try {
    const response = await request.put(`/admin/announcement/update/${row.id}`, {
      ...row,
      isTop: !row.isTop
    })
    if (response.code === 0) {
      ElMessage.success(row.isTop ? '取消置顶成功' : '置顶成功')
      getAnnouncementList()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除公告
const deleteAnnouncement = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.delete(`/admin/announcement/delete/${id}`)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      getAnnouncementList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看详情
const viewDetail = (row) => {
  currentAnnouncement.value = row
  detailVisible.value = true
}

// 获取类型名称
const getTypeName = (type) => {
  const map = {
    notice: '通知',
    announcement: '公告',
    activity: '活动',
    maintenance: '维护'
  }
  return map[type] || type
}

// 获取类型颜色
const getTypeColor = (type) => {
  const map = {
    notice: 'primary',
    announcement: 'success',
    activity: 'warning',
    maintenance: 'danger'
  }
  return map[type] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const map = {
    draft: '草稿',
    published: '已发布',
    withdrawn: '已撤回'
  }
  return map[status] || status
}

// 获取状态颜色
const getStatusColor = (status) => {
  const map = {
    draft: 'info',
    published: 'success',
    withdrawn: 'warning'
  }
  return map[status] || ''
}

onMounted(() => {
  getAnnouncementList()
})
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  padding: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
}

.detail-item.full {
  flex-direction: column;
}

.detail-item .label {
  font-weight: 600;
  color: #666;
  min-width: 100px;
}

.detail-item .value {
  color: #333;
}

.detail-item .content {
  margin-top: 8px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}
</style>
